import { createMessage } from '$components/basic/message';

type ValidFun = () => boolean;
type TagRange = 'email' | 'phone' | 'notnull' | ValidFun;
type ValidEvent = {
	tag: TagRange;
	value: string | number | null | undefined;
	action: (() => void) | null;
};

const validate_match_mapper = {
	email: {
		rule: /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/,
		message: 'the email is not valid'
	},
	phone: {
		rule: /^1[3456789]\d{9}$/,
		message: 'the phone is not valid'
	},
	notnull: {
		rule: {
			test: (value: string | number | null | undefined) =>
				value !== null && value !== undefined && value !== ''
		},
		message: 'the value is not null'
	}
};

export function validate_controller() {
	const list: ValidEvent[] = [];

	const put = (
		tag: TagRange,
		value: string | number | null | undefined,
		action: (() => void) | null = null
	) => {
		list.push({ tag, value, action });
		return result;
	};

	const showMessage = (message: string = '') => {
		createMessage({ type: 'warning', message });
	};

	const check = () => {
		return list.some(({ tag, value, action }) => {
			if (typeof tag === 'string') {
				const { rule, message } = validate_match_mapper[tag];
				// 校验
				if (!rule.test(value as any)) return action ? action() : showMessage(message), true;
			}

			// 自定义函数校验 要求实现 ValidFun 类型
			if (tag instanceof Function && !tag())
				return action ? action() : showMessage('field error'), true;

			return false;
		});
	};

	const result = {
		put,
		check
	};

	return result;
}
